﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Reflection;
using QL_Truong_Hoc;

namespace QL_Truong_Hoc.KhungDaoTao
{
    public partial class frmLopHocNghe : DevExpress.XtraEditors.XtraForm
    {
        private const string mcstrRoleCode = "khung_nghe";

        private clsEnum.FORM_MODE memMode;
        private int mintLopID = -1;
        private int mintKDT = -1;

        public frmLopHocNghe()
        {
            InitializeComponent();
        }

        private void frmLopHoc_Load(object sender, EventArgs e)
        {
            if (!clsCommon.fncCheckRole(Program.glstRoles, mcstrRoleCode))
            {
                this.BeginInvoke(new MethodInvoker(this.Close));
                return;
            }

            // TODO: This line of code loads data into the 'qLTHDataSet.mLopSelectAllWithDetail' table. You can move, or remove it, as needed.
            this.mLopSelectAllWithDetailTableAdapter.Fill(this.qLTHDataSet.mLopSelectAllWithDetail);
            // TODO: This line of code loads data into the 'qLTHDataSet.mNghe' table. You can move, or remove it, as needed.
            this.mNgheTableAdapter.Fill(this.qLTHDataSet.mNghe);
            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoaHoc' table. You can move, or remove it, as needed.
            this.mKhoaHocTableAdapter.Fill(this.qLTHDataSet.mKhoaHoc);
            // TODO: This line of code loads data into the 'qLTHDataSet.mKhoa' table. You can move, or remove it, as needed.
            this.mKhoaTableAdapter.Fill(this.qLTHDataSet.mKhoa);
            // TODO: This line of code loads data into the 'qLTHDataSet.mTrinhDoDaoTao' table. You can move, or remove it, as needed.
            this.mTrinhDoDaoTaoTableAdapter.Fill(this.qLTHDataSet.mTrinhDoDaoTao);

            memMode = clsEnum.FORM_MODE.VIEW;
            xSetFormMode(memMode);
            Program.gevnApplication.evnMasterUpdate += new clsEvents.dgaMasterUpdateHandler(xMasterUpdate);
        }

        private void xMasterUpdate()
        {
            try
            {
                if (!clsCommon.fncMsgConfirm("Danh mục dùng chung đã thay đổi. Bạn có muốn cập nhật mới dữ liệu?")) return;

                // TODO: This line of code loads data into the 'qLTHDataSet.mNghe' table. You can move, or remove it, as needed.
                this.mNgheTableAdapter.Fill(this.qLTHDataSet.mNghe);
                // TODO: This line of code loads data into the 'qLTHDataSet.mKhoaHoc' table. You can move, or remove it, as needed.
                this.mKhoaHocTableAdapter.Fill(this.qLTHDataSet.mKhoaHoc);
                // TODO: This line of code loads data into the 'qLTHDataSet.mKhoa' table. You can move, or remove it, as needed.
                this.mKhoaTableAdapter.Fill(this.qLTHDataSet.mKhoa);
                // TODO: This line of code loads data into the 'qLTHDataSet.mTrinhDoDaoTao' table. You can move, or remove it, as needed.
                this.mTrinhDoDaoTaoTableAdapter.Fill(this.qLTHDataSet.mTrinhDoDaoTao);

                dgvLop.RefreshData();
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xSetFormMode(clsEnum.FORM_MODE emMode)
        {
            bool blnResult = false;
            try
            {
                this.memMode = emMode;

                switch (emMode)
                {
                    case clsEnum.FORM_MODE.VIEW:
                        mniSave.Enabled = false;
                        mniAdd.Enabled = true;
                        mniEdit.Enabled = true;
                        mniDelete.Enabled = true;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                        //set readonly
                        txtChungChi.Properties.ReadOnly = true;
                        txtDiaDiem.Properties.ReadOnly = true;
                        txtQDso.Properties.ReadOnly = true;
                        txtTenLop.Properties.ReadOnly = true;
                        dtpBatDau.Properties.ReadOnly = true;
                        dtpKetThuc.Properties.ReadOnly = true;
                        dtpQDngay.Properties.ReadOnly = true;

                        //clear combobox
                        cbTrinhDo.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                        cbKhoa.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                        cbKhoas.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                        cbNghe.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                        cbTrinhDo.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));
                        cbKhoa.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));
                        cbKhoas.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));
                        cbNghe.SendKey(new KeyEventArgs(Keys.Control | Keys.Delete));

                        //clear control
                        txtTenLop.ResetText();
                        txtQDso.ResetText();
                        txtDiaDiem.ResetText();
                        txtChungChi.ResetText();
                        dtpKetThuc.ResetText();
                        dtpQDngay.ResetText();
                        dtpBatDau.ResetText();

                        break;

                    case clsEnum.FORM_MODE.ADD:
                        mniSave.Enabled = true;
                        mniAdd.Enabled = false;
                        mniEdit.Enabled = false;
                        mniDelete.Enabled = false;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                        //set readonly
                        txtChungChi.Properties.ReadOnly = false;
                        txtDiaDiem.Properties.ReadOnly = false;
                        txtQDso.Properties.ReadOnly = false;
                        txtTenLop.Properties.ReadOnly = false;
                        dtpBatDau.Properties.ReadOnly = false;
                        dtpKetThuc.Properties.ReadOnly = false;
                        dtpQDngay.Properties.ReadOnly = false;

                        //clear control
                        txtTenLop.ResetText();
                        txtQDso.ResetText();
                        txtDiaDiem.ResetText();
                        txtChungChi.ResetText();
                        dtpKetThuc.ResetText();
                        dtpQDngay.ResetText();
                        dtpBatDau.ResetText();

                        break;

                    case clsEnum.FORM_MODE.EDIT:
                        mniSave.Enabled = true;
                        mniAdd.Enabled = false;
                        mniEdit.Enabled = false;
                        mniDelete.Enabled = true;
                        mniCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                        //set readonly
                        txtChungChi.Properties.ReadOnly = false;
                        txtDiaDiem.Properties.ReadOnly = false;
                        txtQDso.Properties.ReadOnly = false;
                        txtTenLop.Properties.ReadOnly = false;
                        dtpBatDau.Properties.ReadOnly = false;
                        dtpKetThuc.Properties.ReadOnly = false;
                        dtpQDngay.Properties.ReadOnly = false;

                        break;
                }

                return true;
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
            return blnResult;
        }

        private void mniSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                //check valid trước khi tiếp tục
                if (!validControlBlank.Validate()) return;

                switch (this.memMode)
                {
                    case clsEnum.FORM_MODE.ADD:
                        if (xAddNew())
                        {
                            //this.mLopSelectAllWithDetailTableAdapter.GetData();
                            this.mLopSelectAllWithDetailTableAdapter.Fill(this.qLTHDataSet.mLopSelectAllWithDetail);
                            xSetFormMode(clsEnum.FORM_MODE.VIEW);
                        }
                        break;

                    case clsEnum.FORM_MODE.EDIT:
                        if (xUpdate())
                        {
                            //this.mLopSelectAllWithDetailTableAdapter.GetData();
                            this.mLopSelectAllWithDetailTableAdapter.Fill(this.qLTHDataSet.mLopSelectAllWithDetail);
                            xSetFormMode(clsEnum.FORM_MODE.VIEW);
                        }
                        break;
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }


        private void mniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                //chọn khung đào tạo
                using (frmChonKhungDaoTao frmChon = new frmChonKhungDaoTao())
                {
                    frmChon.ShowDialog();
                    if (!frmChon.Selected) return;

                    //fill
                    mintKDT = frmChon.KhungDaoTaoID;
                    cbTrinhDo.EditValue = frmChon.TrinhDoDaoTao;
                    cbKhoa.EditValue = frmChon.Khoa;
                    cbKhoas.EditValue = frmChon.Khoas;
                    cbNghe.EditValue = frmChon.Nghe;
                }

                xSetFormMode(clsEnum.FORM_MODE.ADD);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }
        private void mniEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                mintLopID = clsCommon.fncCnvNullToInt(dgvLop.GetFocusedRowCellValue(colLop_ID));

                if (mintLopID <= 0)
                {
                    clsCommon.fncMsgInfo("Hãy chọn một giá trị để sửa.");
                    dgvLop.Focus();
                    return;
                }

                xEdit(mintLopID);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!clsCommon.fncMsgConfirm("Dữ liệu sẽ không được lưu. Bạn có chắc muốn hủy?")) return;

                xSetFormMode(clsEnum.FORM_MODE.VIEW);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private bool xView(int intID)
        {
            bool blnResult = false;
            try
            {
                //lấy dữ liệu
                DTO.MLopDTO objLop = DAO.MLopDAO.Select(Program.gobjDb, intID);
                DTO.MKhungDaoTaoDTO objKhung = DAO.MKhungDaoTaoDAO.Select(Program.gobjDb, objLop.KDT_ID);

                //fill combobox
                cbTrinhDo.EditValue = objKhung.TD_ID;
                cbKhoa.EditValue = objKhung.KH_ID;
                cbKhoas.EditValue = objKhung.KHS_ID;
                cbNghe.EditValue = objKhung.NG_ID;

                //fill detail
                txtChungChi.Text = objLop.Lop_chungchi;
                txtDiaDiem.Text = objLop.Lop_diadiem;
                txtQDso.Text = objLop.Lop_quyetdinh;
                txtTenLop.Text = objLop.Lop_ten;
                dtpBatDau.EditValue = objLop.Lop_batdau;
                dtpKetThuc.EditValue = objLop.Lop_ketthuc;
                dtpQDngay.EditValue = objLop.Lop_quyetdinh_ngay;

                //lưu khung đào tạo
                mintKDT = objKhung.KDT_ID;
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            return blnResult;
        }

        private bool xAddNew()
        {
            bool blnResult = false;
            try
            {
                if (clsCommon.fncMsgConfirm("Dữ liệu sẽ được lưu. Bạn có chắc chắn?"))
                {
                    //thêm mới khung đào tạo
                    DTO.MLopDTO objLop = new DTO.MLopDTO();
                    objLop.KDT_ID = mintKDT;
                    objLop.Lop_ten = txtTenLop.Text;
                    objLop.Lop_batdau = clsCommon.fncCnvNullToDatetime(dtpBatDau.EditValue);
                    objLop.Lop_ketthuc = clsCommon.fncCnvNullToDatetime(dtpKetThuc.EditValue);
                    objLop.Lop_quyetdinh = txtQDso.Text;
                    objLop.Lop_quyetdinh_ngay = clsCommon.fncCnvNullToDatetime(dtpQDngay.EditValue);
                    objLop.Lop_diadiem = txtDiaDiem.Text;
                    objLop.Lop_chungchi = txtChungChi.Text;

                    //insert db khung đào tạo
                    DAO.MLopDAO.Insert(Program.gobjDb, Program.gobjTrans, objLop);

                    return true;
                }
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                clsCommon.fncMsgError("Lưu dữ liệu không thành công. Hãy kiểm tra dữ liệu và thử lại.");
            }
            return blnResult;
        }

        private bool xEdit(int intID)
        {
            bool blnResult = false;
            try
            {
                //hiển thị dữ liệu
                xView(intID);

                //set form sang edit mode
                xSetFormMode(clsEnum.FORM_MODE.EDIT);
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            return blnResult;
        }

        private bool xUpdate()
        {
            bool blnResult = false;
            try
            {
                if (clsCommon.fncMsgConfirm("Dữ liệu sẽ được lưu. Bạn có chắc chắn?"))
                {
                    //thêm mới khung đào tạo
                    DTO.MLopDTO objLop = new DTO.MLopDTO();
                    objLop.Lop_ID = mintLopID;
                    objLop.KDT_ID = mintKDT;
                    objLop.Lop_ten = txtTenLop.Text;
                    objLop.Lop_batdau = clsCommon.fncCnvNullToDatetime(dtpBatDau.EditValue);
                    objLop.Lop_ketthuc = clsCommon.fncCnvNullToDatetime(dtpKetThuc.EditValue);
                    objLop.Lop_quyetdinh = txtQDso.Text;
                    objLop.Lop_quyetdinh_ngay = clsCommon.fncCnvNullToDatetime(dtpQDngay.EditValue);
                    objLop.Lop_diadiem = txtDiaDiem.Text;
                    objLop.Lop_chungchi = txtChungChi.Text;

                    //insert db khung đào tạo
                    DAO.MLopDAO.Update(Program.gobjDb, Program.gobjTrans, objLop);

                    return true;
                }
            }
            catch (Exception ex)
            {
                clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                clsCommon.fncMsgError("Lưu dữ liệu không thành công. Hãy kiểm tra dữ liệu và thử lại.");
            }
            return blnResult;
        }

        private void dgvLop_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                //chỉ kích hoạt ở trạng thái view
                if (this.memMode != clsEnum.FORM_MODE.VIEW) return;

                //chỉ kích hoạt với chuột trái
                if (e.Button != System.Windows.Forms.MouseButtons.Left) return;

                mintLopID = clsCommon.fncCnvNullToInt(dgvLop.GetFocusedRowCellValue(colLop_ID));

                if (mintLopID <= 0)
                { return; }

                xView(mintLopID);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void mniDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                //tìm xem có bao nhiêu lớp trong khung đào tạo. nếu có thì không cho xóa.
                List<DTO.TLopHocSinhDTO> lstHs;
                bool blnHasHS = true;          //cờ xác định xem có lớp hay không
                bool blnSuccess = true;
                int intLopID;

                intLopID = clsCommon.fncCnvNullToInt(dgvLop.GetFocusedRowCellValue(colLop_ID));

                if (intLopID <= 0)
                {
                    clsCommon.fncMsgInfo("Hãy chọn một giá trị để xóa.");
                    dgvLop.Focus();
                    return;
                }

                lstHs = DAO.TLopHocSinhDAO.SelectWhere(Program.gobjDb, string.Format("Lop_ID = {0}", intLopID));

                if (lstHs == null) blnHasHS = false;
                if (lstHs.Count <= 0) blnHasHS = false;

                if (blnHasHS)
                {
                    clsCommon.fncMsgWarning("Đang có học sinh trong lớp này. \nHãy xóa hết học sinh trong lớp trước khi xóa thông tin lớp này.");
                    return;
                }
                else
                {
                    if (!clsCommon.fncMsgConfirm("Bạn có chắc muốn xóa lớp này?")) return;

                    Program.gobjTrans = Program.gobjConn.BeginTransaction();

                    try
                    {
                        blnSuccess = blnSuccess && DAO.MLopDAO.Delete(Program.gobjDb, Program.gobjTrans, intLopID);
                    }
                    catch { Program.gobjTrans.Rollback(); }
                    finally
                    {
                        if (blnSuccess) { Program.gobjTrans.Commit(); btnRefresh_ItemClick(null, null); }
                        else { Program.gobjTrans.Rollback(); clsCommon.fncMsgError("Xóa thông tin lớp thất bại. Xin hãy thử lại."); }
                    }
                }
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                // TODO: This line of code loads data into the 'qLTHDataSet.mLopSelectAllWithDetail' table. You can move, or remove it, as needed.
                this.mLopSelectAllWithDetailTableAdapter.Fill(this.qLTHDataSet.mLopSelectAllWithDetail);
                // TODO: This line of code loads data into the 'qLTHDataSet.mNghe' table. You can move, or remove it, as needed.
                this.mNgheTableAdapter.Fill(this.qLTHDataSet.mNghe);
                // TODO: This line of code loads data into the 'qLTHDataSet.mKhoaHoc' table. You can move, or remove it, as needed.
                this.mKhoaHocTableAdapter.Fill(this.qLTHDataSet.mKhoaHoc);
                // TODO: This line of code loads data into the 'qLTHDataSet.mKhoa' table. You can move, or remove it, as needed.
                this.mKhoaTableAdapter.Fill(this.qLTHDataSet.mKhoa);
                // TODO: This line of code loads data into the 'qLTHDataSet.mTrinhDoDaoTao' table. You can move, or remove it, as needed.
                this.mTrinhDoDaoTaoTableAdapter.Fill(this.qLTHDataSet.mTrinhDoDaoTao);

                memMode = clsEnum.FORM_MODE.VIEW;
                xSetFormMode(memMode);
            }
            catch (Exception ex) { clsCommon.fncMsgError(MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); }
        }
    }
}